//index.js
const app = getApp()
var host = app.globalData.host;
var self = null;
var INIT_COUNT = 30;

Page({
  data: {
    //tabbar
    tabbar: {},
    isIphoneX: app.globalData.isIphoneX,
    showAuth: false,
    titleOverHeight: false,
    
    themeColor: '',
    list: [],
    current: 0,
    nextIndex: 0,
    duration: 500,
    stopScroll: false,
    enableChange: false
  },

  onLoad: function (e) {
    console.log(e)
    //隐藏系统tabbar
    wx.hideTabBar();
    //tabbar调用
    app.editTabbar();
    
    self = this;
    self.getStyle();
    if (wx.getStorageSync("openId")) {
      self.init();
    } else {
      app.wechatLoginCallback = function () {
        self.init();
      }
    }
  },

  getStyle() {
    self.setData({
      themeColor: app.globalData.themeColor
    })
  },

  init() {
    var url = host + '/yq/item/init';
    var params = {
      count: INIT_COUNT
    };
    var success = function (res) {
      var list = res.info;
      for (var i = 0; i < list.length; i ++) {
        if (list[i].tags) {
          var tags = list[i].tags.split(";");
          tags.pop();
          list[i].tags = tags;
        } else {
          list[i].tags = new Array;
        }
      }
      self.setData({
        list: list
      })
      console.log(self.data.list);
      
      self.dealContentClamp();
    }
    var fail = function (res) {};
    var complete = function () {};
    app.request(url, params, success, fail, complete);
    // self.setData({
    //   duration: 500,
    //   current: 2
    // })
  },

  goInfo(e) {
    var itemId = e.currentTarget.dataset.itemid;
    wx.navigateTo({
      url: '/pages/productInfo/productInfo?itemId=' + itemId
    })
  },

  dealContentClamp() {
    var query = wx.createSelectorQuery();
    query.selectAll('.title').boundingClientRect();
    query.exec((res) => {
      var list = self.data.list;
      for (var i = 0; i < res[0].length; i++) {
        if (res[0][i].height > 30) {
          list[i].titleOverHeight = true;
        }
      }
      self.setData({
        list: list
      })
    })
  },

  onauth(e) {
    console.log('au')
    wx.login({
      success(res) {
        if (res.code) {
          // 发起网络请求
          wx.request({
            url: 'https://test.com/onLogin',
            data: {
              code: res.code
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
    wx.getUserInfo({
      success(res) {
        const userInfo = res.userInfo
        const nickName = userInfo.nickName
        const avatarUrl = userInfo.avatarUrl
        const gender = userInfo.gender // 性别 0：未知、1：男、2：女
        const province = userInfo.province
        const city = userInfo.city
        const country = userInfo.country
        console.log(userInfo)
      },
      fail() {
        console.log('fail')
      }
    })
  },

  addFav(e) {
    console.log(e);
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          var itemId = e.currentTarget.dataset.itemid;
          var url = host + '/yq/item/subscribe'
          var params = {
            itemId: itemId
          }
          var success = function (res) {
            var list = self.data.list;
            for (var i = 0; i < list.length; i++) {
              if (list[i].id === itemId) {
                list[i].isSubscribe = 1;
              }
            }
            self.setData({
              list: list
            })
            // wx.showToast({
            //   title: '收藏成功',
            //   icon: 'none'
            // })
          }
          var fail = function (res) { };
          var complete = function () { };
          app.request(url, params, success, fail, complete);

        } else {
          wx.setStorageSync("path", self.route);
          // wx.reLaunch({
          //   url: '/pages/login/login'
          // })
          self.setData({
            showAuth: true
          })
        }
      }
    })
  },

  rmFav(e) {
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          var itemId = e.currentTarget.dataset.itemid;
          var url = host + '/yq/item/unsubscribe'
          var params = {
            itemId: itemId
          }
          var success = function (res) {
            var list = self.data.list;
            for (var i = 0; i < list.length; i++) {
              if (list[i].id === itemId) {
                list[i].isSubscribe = 0;
              }
            }
            self.setData({
              list: list
            })
            // wx.showToast({
            //   title: '取消收藏成功',
            //   icon: 'none'
            // })
          }
          var fail = function (res) { };
          var complete = function () { };
          app.request(url, params, success, fail, complete);

        } else {
          wx.setStorageSync("path", self.route);
          // wx.reLaunch({
          //   url: '/pages/login/login'
          // })
          self.setData({
            showAuth: true
          })
        }
      }
    })
  },

  onCurrentChange(e) {
    var next = e.detail.current;
    // if (e.detail.source == "touch") {
    //   self.setData({
    //     nextIndex: next,
    //     stopScroll: true
    //   })
    //   setTimeout(function() {
    //     self.setData({
    //       stopScroll: false
    //     })
    //   }, 1000)
    // }
    if (next >= INIT_COUNT / 2 && !self.data.enableChange) {
      self.setData({
        enableChange: true
      })
    }
    if ((next > self.data.current || next == 0) && self.data.enableChange) {
      wx.request({
        url: host + '/yq/item',
        data: {},
        success: function(res) {
          var list = self.data.list;
          var index = next - INIT_COUNT / 2;
          if (index < 0) {
            index = INIT_COUNT + index;
          }
          var item = res.data.info;
          if (item.tags) {
            var tags = item.tags.split(";");
            tags.pop();
            item.tags = tags;
          } else {
            item.tags = new Array;
          }
          list[index] = item;
          self.setData({
            list: list
          })
          self.dealContentClamp();
        }
      })
    }

    self.setData({
      current: next
    })
  },

  onAnimeFinish(e) {
    // if (e.detail.source != "touch") {
    //   self.setData({
    //     duration: 500
    //   })
    //   return;
    // }
    // self.setData({
    //   duration: 0
    // })
    // self.setData({
    //   current: 2
    // })

    // var list = self.data.list;
    // if (self.data.nextIndex > self.data.current) {
    //   list.shift();
    //   list.push({});
    // } else if (self.data.nextIndex < self.data.current) {
    //   list.pop();
    //   list.unshift({});
    // }
    // self.setData({
    //   list: list
    // })

    // wx.request({
    //   url: host + '/yq/item',
    //   params: {},
    //   success: function (res) {
    //     var list = self.data.list;
    //     if (self.data.nextIndex > self.data.current) {
    //       list[list.length - 1] = res.data.info;
    //     } else if (self.data.nextIndex < self.data.current) {
    //       list[0] = res.data.info;
    //     }
    //     self.setData({
    //       list: list
    //     })
    //     console.log(self.data.list);
    //   }
    // })
  }
  
})